<!-- TextBox.vue -->
<template>
  <div class="container">
    <div class="head_container">
      <div class="id_container">ID:{{ id }}</div>
      <div class="text_container">对话</div>
    </div>
    <div class="rich_text_container">
      <span>角色名称</span>
      <div>
        <el-select
          v-model="roleNameValue"
          filterable
          clearable
          placeholder="请选择角色名称"
          style="width: 240px"
          @clear="handleRoleClear"
          @change="handleRoleChange(roleNameValue)"
        >
          <el-option
            v-for="item in roleNameOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
    </div>
    <div class="rich_text_container">
      <span>角色昵称</span>
      <div>
        <el-select
          v-model="nickNameValue"
          filterable
          clearable
          :disabled="isSelected"
          placeholder="请选择角色昵称"
          style="width: 240px"
          @change="handleNickNameChange(nickNameValue)"
          @clear="handleNickNameClear"
        >
          <el-option
            v-for="item in nickNameOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
    </div>

    <div class="special-rich_text_container">
      <span>选择头像</span>
      <div
        :class="
          SelectObject?.headImageUrl
            ? 'special-input-disable'
            : 'basic-input-style'
        "
      >
        <el-select
          v-model="headImageValue"
          filterable
          clearable
          :disabled="isSelected"
          placeholder="请选择头像"
          style="width: 240px"
          @change="handleHeadImageChange(headImageValue)"
        >
          <template #prefix>
            <div v-if="headImageValue">
              <img
                :src="headImageValue"
                alt="头像"
                style="width: 30px; height: 30px; margin-right: 10px"
              />
            </div>
          </template>
          <el-option
            v-for="item in headImageOptions"
            :key="item.id"
            label=" "
            :value="item.headUrl"
          >
            <template #default>
              <div style="display: flex; align-items: center">
                <img
                  :src="item.headUrl"
                  alt="头像"
                  style="width: 30px; height: 30px; margin-right: 10px"
                />
              </div>
            </template>
          </el-option>
        </el-select>
      </div>
    </div>
    <div class="dialogue-content-container">
      <span>对话内容</span>
      <div>
        <el-input
          v-model="dialogueContent"
          style="width: 544px; height: 50px; margin-left: 54px"
          placeholder="请输入对话内容"
          class="dialogue-input-container"
        />
      </div>
    </div>
    <div class="rich_text_container">
      <span style="width: 72px; height: 24px; color: #c4c4c4; padding-top: 12px"
        >章节选项</span
      >
      <div class="selected_container">
        <div class="mb-2 flex items-center text-sm">
          <el-radio-group
            v-model="speakDirectionRadio"
            class="ml-8"
            @change="handleChange"
          >
            <el-radio value="1" size="large">左边说话</el-radio>
            <el-radio value="2" size="large">右边说话</el-radio>
          </el-radio-group>
        </div>
      </div>
    </div>
    <div class="rich_text_container">
      <span>下一步&nbsp;&nbsp;&nbsp; </span>
      <div>
        <el-input v-model="nextStep" class="input-disable">下一步</el-input>
      </div>
    </div>
    <button class="saveButton" @click="handleSave()">保存</button>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, PropType, watch } from "vue";
import { ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { getCharacterById } from "@/api/character";

export default defineComponent({
  name: "DialogueEditor",
  props: {
    id: {
      type: String as PropType<string>,
      default: "0000"
    },
    valueFromParent: {
      type: Object as PropType<any>,
      required: true,
      default: {
        moduleValue: {
          value: {
            name: "",
            nickName: "",
            headImage: ""
          }
        },
        moduleNext: ""
      }
    }
  },
  emits: ["save"], // 定义自定义事件
  setup(props, { emit }) {
    const dialogTableVisible = ref(false);
    const gridData = ref([]);
    const route = useRoute();
    const SelectObject = ref<any>(
      props.valueFromParent?.moduleValue?.value || {
        nickName: "",
        roleId: "",
        nickId: "",
        name: "",
        headImage: "",
        roleIndex: "",
        headImageId: "",
        headImageUrl: ""
      }
    );
    const roleData = ref([]);
    const roleNameOptions = ref([]);
    const roleNameValue = ref(
      props.valueFromParent?.moduleValue?.value?.roleIndex || ""
    );

    const nickNameValue = ref(
      props.valueFromParent?.moduleValue?.value?.nickId || ""
    );
    const nickNameOptions = ref([]);
    const headImageValue = ref(
      props.valueFromParent?.moduleValue?.value?.headImageUrl || ""
    );
    const headImageOptions = ref([]);
    const isSelected = ref(true);
    const router = useRouter();
    const defaultNextId =
      props.id.split("-")[0] + "-" + (Number(props.id.split("-")[1]) + 1);
    const nextStep = ref(
      props.valueFromParent?.moduleNext
        ? props.valueFromParent?.moduleNext
        : defaultNextId
    );
    const dialogueContent = ref(
      props.valueFromParent?.moduleValue?.value?.dialogueContent || ""
    );
    const speakDirectionRadio = ref(
      props.valueFromParent?.moduleValue?.value?.speakDirection || "1"
    );
    const handleSelectCharacter = () => {
      //   获取章节
      const scriptId = Number(route.query.scriptId);
      getCharacterById(scriptId).then(res => {
        if (res.code === "0000") {
          gridData.value = res.data.list;
        }
      });
      dialogTableVisible.value = true;
    };
    const handleChange = () => {};

    const handleHeadImageChange = value => {
      console.log(headImageOptions.value);
      if (!isSelected.value) {
        SelectObject.value.headImageUrl = value;
        SelectObject.value.headImageId = headImageOptions.value.find(
          item => item.headUrl === value
        ).id;
      } else {
        SelectObject.value.headImageUrl = "";
      }
    };

    const handleNickNameChange = value => {
      if (!isNaN(value)) {
        SelectObject.value.nickName = nickNameOptions.value[value].label;
        SelectObject.value.nickId = value;
      } else {
        SelectObject.value.nickName = "";
      }
    };
    const handleRoleChange = value => {
      if (!isNaN(value)) {
        nickNameOptions.value = [];
        nickNameValue.value = "";
        headImageOptions.value = [];
        headImageValue.value = "";
        if (roleData.value[value].aliasList.length > 0) {
          roleData.value[value].aliasList.forEach((item, idx) => {
            nickNameOptions.value.push({
              id: idx,
              value: idx,
              label: item.alias
            });
          });
        } else {
          nickNameOptions.value = [];
        }
        if (roleData.value[value].imageList.length > 0) {
          roleData.value[value].imageList.forEach((item, idx) => {
            if (item.image !== null) {
              headImageOptions.value.push({
                id: idx,
                label: idx,
                value: item.image.split("/").pop(),
                headUrl: item.image
              });
            } else {
              headImageOptions.value.push({
                id: idx,
                label: idx,
                value: "",
                headUrl: item.image
              });
            }
          });
        } else {
          nickNameOptions.value = [];
          headImageOptions.value = [];
          nickNameValue.value = 0;
          headImageValue.value = "";
        }
        isSelected.value = false;
        SelectObject.value.roleId = roleData.value[value].id;
        SelectObject.value.roleIndex = value;
      }
    };

    const handleSave = () => {
      SelectObject.value.speakDirection = speakDirectionRadio.value;
      SelectObject.value.dialogueContent = dialogueContent.value;
      props.valueFromParent.moduleValue.value = SelectObject.value;
      props.valueFromParent.moduleNext = nextStep.value;

      const updatedContent = { ...props.valueFromParent };
      emit("save", updatedContent); // 触发save事件并传递
    };
    watch(
      () => props.valueFromParent,
      newVal => {
        if (JSON.stringify(props.valueFromParent?.moduleValue) === "{}") {
          nickNameOptions.value = [];
          nickNameValue.value = "";
          headImageOptions.value = [];
          headImageValue.value = "";
          roleNameValue.value = "";
          dialogueContent.value = "";
          speakDirectionRadio.value = "1";
          isSelected.value = true;
          SelectObject.value = {};
          nextStep.value = newVal?.moduleNext;
        } else {
          nickNameOptions.value = [];
          nickNameValue.value = "";
          headImageOptions.value = [];
          headImageValue.value = "";
          if (
            newVal.moduleValue?.value?.roleIndex !== "" &&
            newVal.moduleValue?.value?.roleId !== ""
          ) {
            isSelected.value = false;
            roleNameValue.value = newVal.moduleValue.value.roleIndex;
            if (
              roleData.value[newVal.moduleValue.value.roleIndex].aliasList
                .length > 0
            ) {
              roleData.value[
                newVal.moduleValue.value.roleIndex
              ].aliasList.forEach((item, idx) => {
                nickNameOptions.value.push({
                  id: idx,
                  value: idx,
                  label: item.alias
                });
              });
            } else {
              nickNameOptions.value = [];
            }
            if (
              roleData.value[newVal.moduleValue.value.roleIndex].imageList
                .length > 0
            ) {
              roleData.value[
                newVal.moduleValue.value.roleIndex
              ].imageList.forEach((item, idx) => {
                if (item.image !== null) {
                  headImageOptions.value.push({
                    id: idx,
                    label: idx,
                    value: item.image.split("/").pop(),
                    headUrl: item.image
                  });
                } else {
                  headImageOptions.value.push({
                    id: idx,
                    label: idx,
                    value: "",
                    headUrl: item.image
                  });
                }
              });
            } else {
              nickNameOptions.value = [];
              headImageOptions.value = [];
              nickNameValue.value = 0;
              headImageValue.value = "";
            }
          }
          if (newVal.moduleValue?.value?.nickId !== "") {
            isSelected.value = false;
            nickNameValue.value = newVal.moduleValue.value.nickId;
          }
          if (newVal.moduleValue?.value?.headImageId !== "") {
            isSelected.value = false;
            headImageValue.value = newVal.moduleValue.value.headImageUrl;
          }
          SelectObject.value = newVal.moduleValue.value;
          nextStep.value = newVal?.moduleNext;
          dialogueContent.value = newVal.moduleValue.value.dialogueContent;
        }
      },
      { deep: true }
    );

    const handleRoleClear = () => {
      isSelected.value = true;
      nickNameValue.value = "";
      headImageValue.value = "";
    };
    const handleNickNameClear = () => {
      nickNameValue.value = "";
    };
    // 获取角色数据
    onMounted(() => {
      const scriptId = Number(route.query.scriptId);
      if (!scriptId) {
        router.push("/error/404");
      } else {
        getCharacterById(scriptId).then(res => {
          if (res.code === "0000") {
            const characterList = res.data.list;
            for (let i = 0; i < characterList.length; i++) {
              const imageArray = JSON.parse(characterList[i].image);
              const aliasArray = JSON.parse(characterList[i].alias);
              roleData.value.push({
                id: characterList[i].id,
                name: characterList[i].name,
                imageList: imageArray,
                aliasList: aliasArray
              });
              roleNameOptions.value.push({
                id: i,
                value: i,
                label: characterList[i].name
              });
            }
            if (props.valueFromParent?.moduleValue?.value?.roleIndex !== -1) {
              if (!props.valueFromParent?.moduleValue?.value) {
                nickNameOptions.value = [];
                nickNameValue.value = "";
                headImageOptions.value = [];
                headImageValue.value = "";
              } else {
                roleNameValue.value =
                  props.valueFromParent?.moduleValue?.value?.roleIndex;
                roleData.value[
                  props.valueFromParent?.moduleValue?.value?.roleIndex
                ].imageList.forEach((item, idx) => {
                  if (item.image !== null) {
                    headImageOptions.value.push({
                      id: idx,
                      label: idx,
                      value: item.image.split("/").pop(),
                      headUrl: item.image
                    });
                  } else {
                    headImageOptions.value.push({
                      id: idx,
                      label: idx,
                      value: "",
                      headUrl: item.image
                    });
                  }
                });
                roleData.value[
                  props.valueFromParent?.moduleValue?.value?.roleIndex
                ].aliasList.forEach((item, idx) => {
                  nickNameOptions.value.push({
                    id: idx,
                    value: idx,
                    label: item.alias
                  });
                });
              }
            } else {
              roleNameValue.value = "";
            }

            if (props.valueFromParent?.moduleValue?.value?.nickId !== -1) {
              nickNameValue.value =
                props.valueFromParent?.moduleValue?.value?.nickId;
              isSelected.value = false;
            } else {
              nickNameValue.value = "";
            }
            if (props.valueFromParent?.moduleValue?.value?.headImageUrl) {
              isSelected.value = false;
              headImageValue.value =
                props.valueFromParent?.moduleValue?.value?.headImageUrl;
            } else {
              headImageValue.value = "";
            }
          }
        });
      }
    });

    return {
      nextStep,
      handleSelectCharacter,
      dialogTableVisible,
      gridData,
      // handleRowClick,
      SelectObject,
      handleSave,
      dialogueContent,
      speakDirectionRadio,
      handleChange,
      roleData,
      roleNameOptions,
      roleNameValue,
      nickNameValue,
      nickNameOptions,
      handleRoleChange,
      headImageValue,
      headImageOptions,
      isSelected,
      handleHeadImageChange,
      handleRoleClear,
      handleNickNameChange,
      handleNickNameClear
    };
  }
});
</script>

<style scoped>
:deep(.el-select__wrapper) {
  background-color: #232323;
  width: 544px;
  height: 50px;
  margin-left: 50px;
}

:deep(.el-select-dropdown__list) {
  background-color: #00cc55 !important;
  width: 544px !important;
}

.selected_container {
  left: 200px;
  top: 115px;
  width: 544px;
  height: 50px;
  opacity: 1;
  border-radius: 10px;
  background: rgba(35, 35, 35, 1);
  margin-left: 50px;
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  padding-left: 100px;
}

.grid-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}
::v-deep .cell {
  display: flex;
}
.v-for-container {
  display: flex;
  .selected-image-container {
    width: 100px;
    border: 1px solid black;
    padding-left: 20px;
  }
}

.input-disable {
  width: 542px;
  min-height: 50px;
  opacity: 1;
  border-radius: 10px;
  margin-left: 55px;
}

.rich_text_container {
  display: flex;
  width: 680px;
  height: 50px;
  margin-left: 66.5px;
  margin-top: 20px;
  span {
    padding-top: 12px;
  }
}
.dialogue-content-container {
  display: flex;
  width: 680px;
  height: 50px;
  margin-left: 66.5px;
  margin-top: 20px;
  span {
    padding-top: 12px;
  }
}

.special-rich_text_container {
  width: 680px;
  height: 50px;
  margin-left: 66.5px;
  margin-top: 20px;
  position: relative; /* 确保相对定位的基准 */
  .special-image-container {
    position: absolute;
    top: -8px; /* 调整这个值以便让图片浮动到合适的位置 */
    left: 130px;
    width: 50px;
    height: 50px;
    z-index: 10; /* 提升层叠顺序 */
  }
  .special-input-disable {
    margin-top: -32px; /* 调整这个值以便与图片有合适的间距 */
    margin-left: 63px; /* 调整这个值以便与图片有合适的间距 */
  }
  .basic-input-style {
    margin-top: -32px; /* 调整这个值以便与图片有合适的间距 */
    margin-left: 63px; /* 调整这个值以便与图片有合适的间距 */
  }
}
.special-input-disable /deep/ .el-input__inner {
  /* 调整 ElementUI 输入框的样式 */
  margin-left: 60px; /* 调整这个值使文字向右移动 */
}

.head_container {
  width: 811px;
  height: 55px;
  background-color: #525252;
  display: flex;
  align-items: center;

  .id_container {
    width: 75px;
    height: 25px;
    color: #a3a3a3;
    margin-left: 20px;
    margin-right: 298.5px;
  }

  .text_container {
    width: 44px;
    height: 30px;
  }
}

.container {
  width: 811px;
  height: 644.7px;
  background-color: #383838;
}

textarea {
  width: 100%;
  box-sizing: border-box;
}

.saveButton {
  height: 60px;
  width: 671px;
  background-color: #ff8d1a;
  color: #78491b;
  margin-left: 66.5px;
  margin-top: 3px;
  border-radius: 10px;
}

html.dark {
  --w-e-textarea-bg-color: #333;
  --w-e-textarea-color: #fff;
}

button {
  background-color: #ff8d1a;
  border: none;
  padding: 10px 20px;
  color: white;
  cursor: pointer;
  border-radius: 4px;
  margin-top: 10px;
}

button:hover {
  background-color: #e67e22;
}
</style>
